#include "system/buffer.h"

namespace dw {
	namespace system {

IBuffer::IBuffer(Usage usage)
:	IResource("Buffer")
,	_usage(usage)
,	_size(0)
,	_data(NULL)
,	_locked(false)
,	_lockedData(0, 0)
,	_lockedSize(0, 0)
{
}

void IBuffer::read(void* dst) const
{
	read(0, _size, dst);
}

void IBuffer::write(const void* src)
{
	write(0, _size, src);
}

void IBuffer::setData(const uint32 lockOffset, const char* data)
{
	lock(0, _size, BA_WRITE_ONLY);
	write(0, _size, data);
	unlock();
}

std::ostream& operator << (std::ostream& os, IBuffer& buffer)
{
	char* data = new char[buffer._size];

	os.write(reinterpret_cast< const char* >(&buffer._usage), sizeof (IBuffer::Usage));
	os.write(reinterpret_cast< const char* >(&buffer._size), sizeof (uint32));
	buffer.lock(0, 0, IBuffer::BA_READ_ONLY);
	buffer.read(data);
	buffer.unlock();
	os.write(data, buffer._size);
	delete[] data;
	return os;
}

std::istream& operator >> (std::istream& is, IBuffer& buffer)
{
	char* data = 0;

	is.read(reinterpret_cast< char* >(&buffer._usage), sizeof (IBuffer::Usage));
	is.read(reinterpret_cast< char* >(&buffer._size), sizeof (uint32));
	data = new char[buffer._size];
	is.read(data, buffer._size);
	buffer.resize(buffer._size);
	buffer.lock(0, 0, IBuffer::BA_WRITE_ONLY);
	buffer.write(data);
	buffer.unlock();
	delete[] data;
	return is;
}

	}
}
